import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class imageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置浏览器3秒刷新
        resp.setHeader("refresh","0.");
        //后台给前台设定一些属性是通过设置响应头的方法

        //java画画
        //先创建画布，在内存中创建一张图片
        BufferedImage bufferedImage = new BufferedImage(1920,1080,BufferedImage.TYPE_INT_RGB);

        //再创建画笔
        Graphics2D g = (Graphics2D) bufferedImage.getGraphics();
        //用之前要设置笔的颜色
//        g.setColor(Color.BLACK);
//        g.fillRect(0,0,160,90);
        //给图片写数据
        g.setColor(Color.RED);
        g.setFont(new Font(null,0,200));
        g.drawString(makeNum(),260,540);

        //告诉浏览器这个响应用浏览器的格式响应
        resp.setContentType("image/jpg");
        //不让浏览器缓存，因为缓存了就读不到最新的了
        resp.setHeader("Cache-Control","no-cache");

        //把图片写出去，ImageIO，专门的图片输出流，三个参数意思是：把哪个图片，以什么格式输出，输出到哪个输出流上
        ImageIO.write(bufferedImage,"jpg",resp.getOutputStream());



    }

    private String makeNum(){
        Random random = new Random();
        String num = random.nextInt(99999999) + "";
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<8-num.length();i++){
            sb.append(0);
        }
        num = sb.toString() + num;
        //以上的操作在不足8位长度的数前补0
        return num;


    }


}
